## DEPRECATED

import os
import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import time
from time import strftime

import diffmodule2 as dm ## Classes for "fluxArray" and "starObj"

def pstr(num,pad):
    strlen = len(str(num))
    lenpad = pad-strlen
    return str((lenpad*'0')+str(num))

def trunc(f, n):
    '''Truncates a float f to n decimal places without rounding'''
    slen = len('%.*f' % (n, f))
    return str(f)[:slen]

plots = 'on'

print "Computing differential photometry..."
os.system('mkdir diff10')

os.system("ls aper_out/*.log > filelists/aperfiles.txt")
flxfiles = open('filelists/aperfiles.txt','r').read().splitlines()
for j in range(1,len(flxfiles)+1):
    teststar = dm.starObj(pstr(j,3))        ## Initialize star object for test star
    testflux = dm.fluxArr(teststar)         ## Initialize flux object for test star
    testflux.avgFlux(teststar)              ## Add test star's flux to flux obj

    starobjs = []
    for i in range(2,len(flxfiles)+1):
        if i != j:                                    ## For stars other than test star,
            starobjs.append(dm.starObj(pstr(i,3)))    ## create star objs

    controlflux = dm.fluxArr(starobjs[0])   ## Initialize a flux object for the
                                            ## control stars
    for i in starobjs:
        if i.flags() == False:        ## Include control stars in the flux average
            controlflux.avgFlux(i)    ## that don't have flags

    diff = controlflux.magScale() - testflux.magScale()
                                            ## Take the difference of the log magnitudes
    diffobj = dm.diffArr(diff)
    diffobj.calcMedian(10)

## Prepare plots
    if plots == 'on':
        if teststar.flags() == False:
            errwarn = ''
        else:
            errwarn = 'DISCARDED'

        star_coords = trunc(teststar.trackx()[0,0],0)+', '+trunc(teststar.tracky()[0,0],0)
        figtext = ("Init pixel coords: ("+star_coords+") "+errwarn+"\n"
                   "Generated: "+strftime("%d %b %Y %H:%M", time.localtime())+'')
        
        fig = plt.figure()
        bbox_props = dict(boxstyle="square", fc="white", lw=1, alpha=0.7)
        t = fig.text(0.15, 0.17, figtext, ha="left", va="center", rotation=0,
                    size=12, bbox=bbox_props)

        p1 = plt.plot(diffobj.arr(),'yo')
        p2 = plt.plot(diffobj.medianx(),diffobj.mediany(),'bo-')
        dev = np.std(diffobj.arr())*2
        plt.ylim(np.mean(diffobj.arr())-2*dev,np.mean(diffobj.arr())+2*dev)
        plt.legend((p1[0],p2[0]),("Differential Magnitude",
                                  str(10)+" pt Median"),numpoints=1)
        plt.title('20110608 Plot '+str(j))
        plt.xlabel('Time (min)')
        plt.ylabel('Magnitude (apparent mag. + arbitrary constant)')
        plt.savefig('diff10/plotdiff'+pstr(j,3)+errwarn+'.pdf')

print "Done"
